package org.huanletao.ssm.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.huanletao.ssm.model.RespBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * </p>
 * package: org.huanletao.ssm.controller
 * description:
 * className: LoginController
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/8/27 15:17
 * since: 1.0.0
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);


    @RequestMapping("/login")
    public String login(Model model) {
        return "login";
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                throw new UnknownAccountException("用户名不存在");
            }
            if (e instanceof IncorrectCredentialsException) {
                throw new IncorrectCredentialsException("密码错误");
            }
            throw e;
        }

        return RespBean.ok("登录成功");
    }

    @GetMapping("/logout")
    @ResponseBody
    public RespBean logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return RespBean.ok("退出登录成功");
    }


}
